const { ipcRenderer, dialog } = require('electron');
const hljs = require('highlight.js');
const path = require('path');
const fs = require('fs');

// DOM 元素
const dropArea = document.getElementById('dropArea');
const browseBtn = document.getElementById('browseBtn');
const directoryStructure = document.getElementById('directoryStructure');
const treeView = document.getElementById('treeView');
const contentTitle = document.getElementById('contentTitle');
const overviewContent = document.getElementById('overviewContent');
const environmentInfo = document.getElementById('environmentInfo');
const envContent = document.getElementById('envContent');
const problemDescription = document.getElementById('problemDescription');
const descriptionContent = document.getElementById('descriptionContent');
const logContent = document.getElementById('logContent');
// fileContent元素已移除，只使用React方案
const imageViewer = document.getElementById('imageViewer');
const imageContent = document.getElementById('imageContent');
// 旧的搜索相关DOM元素和变量已删除，现在由React LogViewer组件提供搜索功能

// 全局变量
let currentLoggerPath = null;

// Header右侧控制函数
function showLogAnalysisButton() {
  const logAnalysisBtn = document.getElementById('logAnalysisBtn');
  const headerSearchContainer = document.getElementById('headerSearchContainer');
  
  if (logAnalysisBtn) {
    logAnalysisBtn.classList.remove('d-none');
  }
  if (headerSearchContainer) {
    headerSearchContainer.classList.add('d-none');
  }
}

function showHeaderSearch() {
  const logAnalysisBtn = document.getElementById('logAnalysisBtn');
  const headerSearchContainer = document.getElementById('headerSearchContainer');
  
  if (logAnalysisBtn) {
    logAnalysisBtn.classList.add('d-none');
  }
  if (headerSearchContainer) {
    headerSearchContainer.classList.remove('d-none');
  }
}

function hideAllHeaderActions() {
  const logAnalysisBtn = document.getElementById('logAnalysisBtn');
  const headerSearchContainer = document.getElementById('headerSearchContainer');
  
  if (logAnalysisBtn) {
    logAnalysisBtn.classList.add('d-none');
  }
  if (headerSearchContainer) {
    headerSearchContainer.classList.add('d-none');
  }
}

// 日志分析按钮点击事件
function handleLogAnalysisClick() {
  alert('TODO: 日志分析功能待实现');
}

// 隐藏所有内容区域
function hideAllContentAreas() {
  overviewContent.classList.add('d-none');
  environmentInfo.classList.add('d-none');
  problemDescription.classList.add('d-none');
  logContent.classList.add('d-none');
  imageViewer.classList.add('d-none');
}

// 显示概述页面
function showOverview() {
  hideAllContentAreas();
  contentTitle.textContent = '概述';
  overviewContent.classList.remove('d-none');
  hideAllHeaderActions();
}

// 加载指示器函数
function showLoadingIndicator() {
  // 检查是否已存在加载指示器
  let loadingIndicator = document.getElementById('loadingIndicator');
  
  if (!loadingIndicator) {
    // 创建加载指示器
    loadingIndicator = document.createElement('div');
    loadingIndicator.id = 'loadingIndicator';
    loadingIndicator.className = 'loading-indicator';
    loadingIndicator.innerHTML = `
      <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">加载中...</span>
      </div>
      <div class="mt-2">正在处理文件，请稍候...</div>
    `;
    document.body.appendChild(loadingIndicator);
  } else {
    loadingIndicator.style.display = 'flex';
  }
}

function hideLoadingIndicator() {
  const loadingIndicator = document.getElementById('loadingIndicator');
  if (loadingIndicator) {
    loadingIndicator.style.display = 'none';
  }
}

// 拖放事件处理
dropArea.addEventListener('dragover', (e) => {
  e.preventDefault();
  e.stopPropagation();
  dropArea.classList.add('highlight');
});

dropArea.addEventListener('dragleave', (e) => {
  e.preventDefault();
  e.stopPropagation();
  dropArea.classList.remove('highlight');
});

dropArea.addEventListener('drop', (e) => {
  e.preventDefault();
  e.stopPropagation();
  dropArea.classList.remove('highlight');
  
  if (e.dataTransfer.files.length > 0) {
    const filePath = e.dataTransfer.files[0].path;
    const fileExtension = path.extname(filePath).toLowerCase();
    
    if (fileExtension === '.zip') {
      // 处理ZIP文件
      processZipFile(filePath);
    } else {
      // 处理普通文件夹
      processLoggerFolder(filePath);
    }
  }
});

// 浏览按钮点击事件
browseBtn.addEventListener('click', () => {
  // 打开文件选择对话框，允许选择文件夹或ZIP文件
  dialog.showOpenDialog({
    properties: ['openFile', 'openDirectory'],
    filters: [
      { name: '日志文件', extensions: ['zip'] },
      { name: '所有文件', extensions: ['*'] }
    ]
  }).then(result => {
    if (!result.canceled && result.filePaths.length > 0) {
      const selectedPath = result.filePaths[0];
      const fileExtension = path.extname(selectedPath).toLowerCase();
      
      if (fileExtension === '.zip') {
        // 处理ZIP文件
        processZipFile(selectedPath);
      } else {
        // 处理普通文件夹
        processLoggerFolder(selectedPath);
      }
    }
  }).catch(err => {
    console.error('打开文件对话框时出错:', err);
    alert(`打开文件对话框时出错: ${err.message}`);
  });
});

// 接收选择的目录（保留此代码以兼容旧版本）
ipcRenderer.on('selected-directory', (event, dirPath) => {
  processLoggerFolder(dirPath);
});

// 处理菜单中的打开文件夹事件
ipcRenderer.on('menu-open-directory', () => {
  // 打开文件选择对话框，允许选择文件夹或ZIP文件
  dialog.showOpenDialog({
    properties: ['openFile', 'openDirectory'],
    filters: [
      { name: '日志文件', extensions: ['zip'] },
      { name: '所有文件', extensions: ['*'] }
    ]
  }).then(result => {
    if (!result.canceled && result.filePaths.length > 0) {
      const selectedPath = result.filePaths[0];
      const fileExtension = path.extname(selectedPath).toLowerCase();
      
      if (fileExtension === '.zip') {
        // 处理ZIP文件
        processZipFile(selectedPath);
      } else {
        // 处理普通文件夹
        processLoggerFolder(selectedPath);
      }
    }
  }).catch(err => {
    console.error('打开文件对话框时出错:', err);
    alert(`打开文件对话框时出错: ${err.message}`);
  });
});

// 处理ZIP文件
async function processZipFile(zipFilePath) {
  try {
    // 显示加载提示
    showLoadingIndicator();
    
    // 调用主进程解压ZIP文件
    const result = await ipcRenderer.invoke('process-zip-file', zipFilePath);
    
    if (result.error) {
      throw new Error(result.error);
    }
    
    // 设置当前路径为解压后的临时目录
    currentLoggerPath = result.extractPath;
    
    // 重组目录结构为三个部分：问题概述、Tombstone和logger
    const organizedStructure = organizeStructure(result.structure);
    
    // 显示目录结构
    directoryStructure.classList.remove('d-none');
    renderDirectoryTree(organizedStructure);
    
    // 查找并显示 readme.txt
    findAndDisplayReadme(result.structure);
    
    // 隐藏加载提示
    hideLoadingIndicator();
  } catch (error) {
    console.error('处理ZIP文件时出错:', error);
    alert(`处理ZIP文件时出错: ${error.message}`);
    hideLoadingIndicator();
  }
}

// 处理 logger 文件夹
async function processLoggerFolder(folderPath) {
  try {
    // 显示加载提示
    showLoadingIndicator();
    
    currentLoggerPath = folderPath;
    const structure = await ipcRenderer.invoke('read-directory', folderPath);
    
    // 重组目录结构为三个部分：问题概述、Tombstone和logger
    const organizedStructure = organizeStructure(structure);
    
    // 显示目录结构
    directoryStructure.classList.remove('d-none');
    renderDirectoryTree(organizedStructure);
    
    // 查找并显示 readme.txt
    findAndDisplayReadme(structure);
    
    // 隐藏加载提示
    hideLoadingIndicator();
  } catch (error) {
    console.error('处理文件夹时出错:', error);
    alert(`处理文件夹时出错: ${error.message}`);
    hideLoadingIndicator();
  }
}

// 将文件结构组织为三个部分：概述、crash和logger
function organizeStructure(originalStructure) {
  // 创建三个主要分类
  const organizedStructure = [
    {
      name: '概述',
      path: currentLoggerPath + '/概述',
      type: 'file', // 改为文件类型而非目录
      extension: '.overview',
      isOverview: true,
      readmeFile: null,
      screenshots: []
    },
    {
      name: 'crash',
      path: currentLoggerPath + '/crash',
      type: 'directory',
      children: [],
      isCollapsible: true,
      isExpanded: true
    },
    {
      name: 'logger',
      path: currentLoggerPath + '/logger',
      type: 'directory',
      children: [],
      isCollapsible: true,
      isExpanded: true
    }
  ];
  
  // 遍历原始结构，将文件分类
  function categorizeItems(items) {
    for (const item of items) {
      if (item.type === 'file') {
        // readme.txt 保存引用但不显示在左侧结构中
        if (item.name.toLowerCase() === 'readme.txt') {
          organizedStructure[0].readmeFile = item;
        }
        // 图片文件保存引用但不显示在左侧结构中
        else if (['.png', '.jpg', '.jpeg', '.gif'].includes(item.extension)) {
          organizedStructure[0].screenshots.push(item);
        }
        // air_zip_date.zip 不显示在左侧结构中
        else if (item.name.toLowerCase() === 'air_zip_date.zip') {
          // 不添加到任何分类
        }
        // 崩溃相关日志放入 crash 分类
        else if (item.path.includes('/crash/') || 
                 item.name.toLowerCase().includes('crash') || 
                 item.name.toLowerCase().includes('tombstone')) {
          organizedStructure[1].children.push(item);
        }
        // 其他日志文件放入 logger 分类
        else if (item.extension === '.log' || 
                 item.path.includes('/logs/') || 
                 item.name.toLowerCase().includes('log')) {
          organizedStructure[2].children.push(item);
        }
      } else if (item.type === 'directory' && item.children) {
        // 递归处理子目录
        categorizeItems(item.children);
      }
    }
    
    // 限制截图数量为最多3张
    if (organizedStructure[0].screenshots.length > 3) {
      organizedStructure[0].screenshots = organizedStructure[0].screenshots.slice(0, 3);
    }
  }
  
  categorizeItems(originalStructure);
  return organizedStructure;
}

// 渲染目录树
function renderDirectoryTree(items) {
  treeView.innerHTML = '';
  renderTreeItems(items, treeView);
}

// 递归渲染树项目
function renderTreeItems(items, parentElement) {
  items.forEach(item => {
    const itemElement = document.createElement('div');
    itemElement.className = 'tree-item';
    itemElement.dataset.path = item.path;
    itemElement.dataset.type = item.type;
    
    // 创建文件名容器，防止长文件名换行
    const itemContentDiv = document.createElement('div');
    itemContentDiv.className = 'tree-item-content';
    itemElement.appendChild(itemContentDiv);
    
    const iconSpan = document.createElement('span');
    iconSpan.className = 'tree-icon';
    
    // 概述特殊处理
    if (item.isOverview) {
      iconSpan.innerHTML = '📝 ';
      itemContentDiv.appendChild(iconSpan);
      itemContentDiv.appendChild(document.createTextNode(item.name));
      
      // 添加点击事件
      itemElement.addEventListener('click', () => {
        // 移除所有活动项的高亮
        document.querySelectorAll('.tree-item.active').forEach(el => {
          el.classList.remove('active');
        });
        
        // 高亮当前项
        itemElement.classList.add('active');
        
        // 显示概述页面（readme和截图）
        displayOverviewContent(item);
      });
    }
    // 目录处理
    else if (item.type === 'directory') {
      iconSpan.innerHTML = '📁 ';
      itemContentDiv.appendChild(iconSpan);
      
      // 为crash和logger文件夹添加文件数量显示
      if ((item.name === 'crash' || item.name === 'logger') && item.children) {
        const fileCount = item.children.length;
        itemContentDiv.appendChild(document.createTextNode(`${item.name} (${fileCount})`));
      } else {
        itemContentDiv.appendChild(document.createTextNode(item.name));
      }
      
      // 如果是可折叠的目录，添加折叠图标
      if (item.isCollapsible) {
        const collapseIcon = document.createElement('span');
        collapseIcon.className = item.isExpanded ? 'collapse-icon expanded' : 'collapse-icon collapsed';
        itemContentDiv.appendChild(collapseIcon);
        
        // 添加整个区域的折叠/展开点击事件
        itemContentDiv.addEventListener('click', () => {
          const childrenContainer = itemElement.querySelector('.tree-children');
          if (childrenContainer) {
            if (item.isExpanded) {
              childrenContainer.style.display = 'none';
              collapseIcon.className = 'collapse-icon collapsed';
            } else {
              childrenContainer.style.display = 'block';
              collapseIcon.className = 'collapse-icon expanded';
            }
            item.isExpanded = !item.isExpanded;
          }
        });
      }
      
      const childrenContainer = document.createElement('div');
      childrenContainer.className = 'tree-children';
      if (item.isCollapsible && !item.isExpanded) {
        childrenContainer.style.display = 'none';
      }
      itemElement.appendChild(childrenContainer);
      
      if (item.children && item.children.length > 0) {
        renderTreeItems(item.children, childrenContainer);
      }
    } 
    // 文件处理
    else {
      // 根据文件类型设置图标
      if (['.png', '.jpg', '.jpeg', '.gif'].includes(item.extension)) {
        iconSpan.innerHTML = '🖼️ ';
      } else if (item.extension === '.txt') {
        iconSpan.innerHTML = '📄 ';
      } else if (item.extension === '.log') {
        iconSpan.innerHTML = '📋 ';
      } else {
        iconSpan.innerHTML = '📄 ';
      }
      
      itemContentDiv.appendChild(iconSpan);
      itemContentDiv.appendChild(document.createTextNode(item.name));
      
      // 添加点击事件
      itemElement.addEventListener('click', () => {
        // 移除所有活动项的高亮
        document.querySelectorAll('.tree-item.active').forEach(el => {
          el.classList.remove('active');
        });
        
        // 高亮当前项
        itemElement.classList.add('active');
        
        // 显示文件内容
        displayFileContent(item);
      });
    }
    
    parentElement.appendChild(itemElement);
  });
}

// 查找并显示 readme.txt
function findAndDisplayReadme(items) {
  const findReadme = (items) => {
    for (const item of items) {
      if (item.type === 'file' && item.name.toLowerCase() === 'readme.txt') {
        return item;
      } else if (item.type === 'directory' && item.children) {
        const found = findReadme(item.children);
        if (found) return found;
      }
    }
    return null;
  };
  
  // 查找所有截图
  const findScreenshots = (items) => {
    const screenshots = [];
    for (const item of items) {
      if (item.type === 'file' && ['.png', '.jpg', '.jpeg', '.gif'].includes(item.extension)) {
        screenshots.push(item);
      } else if (item.type === 'directory' && item.children) {
        screenshots.push(...findScreenshots(item.children));
      }
    }
    return screenshots;
  };
  
  const readmeFile = findReadme(items);
  const screenshots = findScreenshots(items).slice(0, 3); // 最多取3张截图
  
  // 找到概述项并高亮显示
  const overviewItem = document.querySelector('.tree-item[data-path*="/概述"]');
  if (overviewItem) {
    // 移除所有活动项的高亮
    document.querySelectorAll('.tree-item.active').forEach(el => {
      el.classList.remove('active');
    });
    
    // 高亮概述项
    overviewItem.classList.add('active');
    
    // 显示概述内容
    const overviewData = {
      readmeFile: readmeFile,
      screenshots: screenshots
    };
    
    displayOverviewContent(overviewData);
  } else if (readmeFile) {
    // 如果没有找到概述项但有readme文件，显示readme内容
    displayFileContent(readmeFile);
  }
}

// 显示概述内容（readme和截图）
async function displayOverviewContent(item) {
  try {
    // 显示概述页面
    hideAllContentAreas();
    contentTitle.textContent = '问题概述';
    
    // 清空概述内容
    overviewContent.innerHTML = '';
    overviewContent.classList.remove('d-none');
    
    // 显示日志分析按钮
    showLogAnalysisButton();
    
    // 如果有readme文件，显示其内容
    if (item.readmeFile) {
      const content = await ipcRenderer.invoke('read-file', item.readmeFile.path);
      
      // 解析readme内容获取结构化数据
      const lines = content.split('\n');
      let problemInfo = {
        time: '',
        type: '',
        description: ''
      };
      let envLines = [];
      
      // 找到 AIR_SN 的位置，以此为分界线
      let airSnIndex = -1;
      for (let i = 0; i < lines.length; i++) {
        if (lines[i].includes('AIR_SN')) {
          airSnIndex = i;
          break;
        }
      }
      
      // 分割内容：AIR_SN 之前为问题描述部分，AIR_SN 及之后为环境信息部分
      const problemLines = airSnIndex >= 0 ? lines.slice(0, airSnIndex) : lines;
      const envContentLines = airSnIndex >= 0 ? lines.slice(airSnIndex) : [];
      
      // 解析问题描述部分
      let descriptionStarted = false;
      let descriptionLines = [];
      
      for (const line of problemLines) {
        if (line.includes('时间')) {
          const parts = line.split(/:|：/);
          if (parts.length >= 2) {
            problemInfo.time = parts.slice(1).join(':').trim();
          }
          continue;
        } else if (line.includes('问题')) {
          const parts = line.split(/:|：/);
          if (parts.length >= 2) {
            problemInfo.type = parts.slice(1).join(':').trim();
          }
          continue;
        } else if (line.includes('描述:') || line.includes('描述：')) {
          const parts = line.split(/:|：/);
          if (parts.length >= 2) {
            const firstLineDesc = parts.slice(1).join(':').trim();
            if (firstLineDesc) {
              descriptionLines.push(firstLineDesc);
            }
          }
          descriptionStarted = true;
          continue;
        } else if (descriptionStarted && line.trim() !== '') {
          descriptionLines.push(line.trim());
        }
      }
      
      problemInfo.description = descriptionLines.join('\n');
      
      // 处理环境信息部分
      for (const line of envContentLines) {
        if (line.trim() !== '') {
          envLines.push(line);
        }
      }
      
      // 创建表格
      const table = document.createElement('table');
      table.className = 'overview-table';
      
      // 添加时间和类型行
      if (problemInfo.time || problemInfo.type) {
        const timeTypeRow = document.createElement('tr');
        timeTypeRow.innerHTML = `
          <td class="key-cell">时间</td>
          <td class="value-cell">${escapeHtml(problemInfo.time)}</td>
          <td class="key-cell">类型</td>
          <td class="value-cell">${escapeHtml(problemInfo.type)}</td>
        `;
        table.appendChild(timeTypeRow);
      }
      
      // 添加描述行
      if (problemInfo.description) {
        const descRow = document.createElement('tr');
        descRow.className = 'description-row';
        descRow.innerHTML = `
          <td class="key-cell">描述</td>
          <td class="value-cell description-cell" colspan="3">
            <div class="description-value" id="problem-description-text">${escapeHtml(problemInfo.description).replace(/\n/g, '<br>')}</div>
            <div class="action-buttons">
              <button class="btn btn-sm btn-outline-primary copy-btn" onclick="copyDescription()">复制</button>
              <button class="btn btn-sm btn-outline-primary translate-btn" onclick="translateDescription()">翻译</button>
            </div>
          </td>
        `;
        table.appendChild(descRow);
        
        // 添加译文行（初始隐藏）
        const translationRow = document.createElement('tr');
        translationRow.className = 'problem-translation';
        translationRow.id = 'problem-translation';
        translationRow.innerHTML = `
          <td class="key-cell">译文</td>
          <td class="value-cell" colspan="3" id="translation-result"></td>
        `;
        table.appendChild(translationRow);
      }
      
      // 添加环境信息行
      for (let i = 0; i < envLines.length; i += 2) {
        const envRow = document.createElement('tr');
        let rowHtml = '';
        
        // 第一个键值对
        const parts1 = envLines[i].split(/:|：/);
        if (parts1.length >= 2) {
          rowHtml += `<td class="key-cell">${escapeHtml(parts1[0])}</td><td class="value-cell">${escapeHtml(parts1.slice(1).join(':').trim())}</td>`;
        } else {
          rowHtml += `<td class="key-cell"></td><td class="value-cell">${escapeHtml(envLines[i])}</td>`;
        }
        
        // 第二个键值对（如果存在）
        if (i + 1 < envLines.length) {
          const parts2 = envLines[i + 1].split(/:|：/);
          if (parts2.length >= 2) {
            rowHtml += `<td class="key-cell">${escapeHtml(parts2[0])}</td><td class="value-cell">${escapeHtml(parts2.slice(1).join(':').trim())}</td>`;
          } else {
            rowHtml += `<td class="key-cell"></td><td class="value-cell">${escapeHtml(envLines[i + 1])}</td>`;
          }
        } else {
          rowHtml += `<td class="key-cell"></td><td class="value-cell"></td>`;
        }
        
        envRow.innerHTML = rowHtml;
        table.appendChild(envRow);
      }
      
      overviewContent.appendChild(table);
    }
    
    // 创建截图部分（无论是否有截图都显示）
    const screenshotsSection = document.createElement('div');
    screenshotsSection.className = 'overview-section';
    screenshotsSection.innerHTML = `
      <h5>📸 截图</h5>
      <div class="card">
        <div class="card-body">
          <div class="screenshots-grid"></div>
        </div>
      </div>
    `;
    
    const screenshotsGrid = screenshotsSection.querySelector('.screenshots-grid');
    
    // 如果有截图，水平均匀分布显示最多三张截图
    if (item.screenshots && item.screenshots.length > 0) {
      // 限制最多显示3张截图
      const screenshots = item.screenshots.slice(0, 3);
      
      // 添加截图到网格中
      screenshots.forEach(screenshot => {
        const imgContainer = document.createElement('div');
        imgContainer.className = 'screenshot-item';
        
        const img = document.createElement('img');
        img.src = `file://${screenshot.path}`;
        img.alt = screenshot.name;
        img.title = screenshot.name;
        imgContainer.appendChild(img);
        
        // 添加点击放大功能
        img.addEventListener('click', () => {
          showLightbox(screenshot);
        });
        
        screenshotsGrid.appendChild(imgContainer);
      });
    } else {
      // 如果没有截图，显示"暂无数据"
        const noDataContainer = document.createElement('div');
        noDataContainer.className = 'no-data-container';
        noDataContainer.textContent = '暂无数据';
        screenshotsGrid.appendChild(noDataContainer);
    }
    
    overviewContent.appendChild(screenshotsSection);
    
    // 创建或获取灯箱容器（用于放大显示图片）
    let lightbox = document.getElementById('lightbox');
    if (!lightbox) {
      lightbox = document.createElement('div');
      lightbox.id = 'lightbox';
      lightbox.className = 'lightbox';
      lightbox.style.display = 'none';
      lightbox.innerHTML = `
        <div class="lightbox-content">
          <span class="close-lightbox">&times;</span>
          <img id="lightbox-img" class="lightbox-img">
          <div id="lightbox-caption" class="lightbox-caption"></div>
        </div>
      `;
      document.body.appendChild(lightbox);
      
      // 添加关闭按钮事件
      const closeBtn = lightbox.querySelector('.close-lightbox');
      closeBtn.addEventListener('click', () => {
        lightbox.style.display = 'none';
      });
      
      // 点击灯箱背景关闭
      lightbox.addEventListener('click', (e) => {
        if (e.target === lightbox) {
          lightbox.style.display = 'none';
        }
      });
    }
  } catch (error) {
    console.error('显示概述内容时出错:', error);
    alert(`显示概述内容时出错: ${error.message}`);
  }
}

// 显示灯箱（放大图片）
function showLightbox(screenshot) {
  const lightbox = document.getElementById('lightbox');
  const lightboxImg = document.getElementById('lightbox-img');
  const lightboxCaption = document.getElementById('lightbox-caption');
  
  lightboxImg.src = `file://${screenshot.path}`;
  lightboxCaption.textContent = screenshot.name;
  lightbox.style.display = 'flex';
}

// 显示文件内容
async function displayFileContent(file) {
  try {
    // 隐藏所有内容区域
    hideAllContentAreas();
    
    // 图片文件
    if (['.png', '.jpg', '.jpeg', '.gif'].includes(file.extension)) {
      contentTitle.textContent = file.name;
      imageViewer.classList.remove('d-none');
      imageContent.src = `file://${file.path}`;
      return;
    }
    
    // 文本文件
    const result = await ipcRenderer.invoke('read-file', file.path);
    
    // 检查是否返回错误
    if (result && result.error) {
      throw new Error(`读取文件失败: ${result.error}`);
    }
    
    const content = result;
    
    // 显示日志内容区域
    contentTitle.textContent = file.name;
    logContent.classList.remove('d-none');
    
    // 如果是 readme.txt，解析环境信息和问题描述
    if (file.name.toLowerCase() === 'readme.txt') {
      parseReadmeContent(content);
    }
    
    // 确定日志类型并应用相应的样式
    let logClass = '';
    let logType = 'other';
    // 根据新的三块结构确定日志类型
    if (isTombstoneLog(file)) {
      logClass = 'crash-log';
      logType = 'crash';
    } else if (isAppLog(file)) {
      logClass = 'app-log';
      logType = 'logger';
    }
    
    // 根据文件类型控制header右侧显示
    if (logType === 'crash') {
      hideAllHeaderActions();
    } else if (logType === 'logger') {
      showHeaderSearch();
    } else {
      hideAllHeaderActions();
    }
    
    // 辅助函数：判断是否为崩溃日志
    function isTombstoneLog(file) {
      return file.path.includes('/crash/') || 
             file.name.toLowerCase().includes('crash') || 
             file.name.toLowerCase().includes('tombstone') || 
             // 如果文件在我们组织的Tombstone目录中
             (file.path.includes('/Tombstone') && file.path.includes(currentLoggerPath));
    }
    
    // 辅助函数：判断是否为应用日志
    function isAppLog(file) {
      return file.path.includes('/logs/') || 
             (file.extension === '.log' && !isTombstoneLog(file)) || 
             // 如果文件在我们组织的logger目录中
             (file.path.includes('/logger') && file.path.includes(currentLoggerPath));
    }
    
    // 检查是否为日志文件
    const isLogFile = content.includes('DEBUG') || 
                     content.includes('INFO') || 
                     content.includes('WARN') || 
                     content.includes('ERROR') || 
                     content.includes('FATAL');
    
    // 使用 React LogViewer 组件显示日志
    const reactLogContainer = document.getElementById('react-log-container');
    
    // 检查React组件是否可用
    if (!reactLogContainer) {
      console.error('React容器未找到: react-log-container');
      throw new Error('React日志容器未找到，请检查HTML结构');
    }

    // 调试信息
    console.log('React库检查:', {
      React: typeof window.React,
      ReactDOM: typeof window.ReactDOM,
      LogViewerComponents: typeof window.LogViewerComponents
    });

    if (!window.React) {
      console.error('React库未加载');
      throw new Error('React库未加载，请检查React CDN链接');
    }

    if (!window.ReactDOM) {
      console.error('ReactDOM库未加载');
      throw new Error('ReactDOM库未加载，请检查ReactDOM CDN链接');
    }

    if (!window.LogViewerComponents) {
      console.error('React组件未加载: window.LogViewerComponents');
      throw new Error('React组件未加载，请检查组件初始化');
    }
    
    if (!window.LogViewerComponents.renderLogViewer) {
      console.error('renderLogViewer方法未找到');
      throw new Error('renderLogViewer方法未找到，请检查组件导出');
    }
    
    console.log('使用React方案显示日志');
    
    // 显示 React 容器
    reactLogContainer.style.display = 'block';
    
    // 渲染 React LogViewer 组件
    try {
      window.LogViewerComponents.renderLogViewer({
        content: content,
        logType: logType,
        fileName: file.name
      });
      console.log('React组件渲染成功');
    } catch (error) {
      console.error('React组件渲染失败:', error);
      throw new Error(`React组件渲染失败: ${error.message}`);
    }
  } catch (error) {
    console.error('显示文件内容时出错:', error);
    alert(`显示文件内容时出错: ${error.message}`);
  }
}

// 解析 readme.txt 内容
function parseReadmeContent(content, returnResult = false) {
  const lines = content.split('\n');
  let envLines = [];
  let descLines = [];
  let problemInfo = {
    time: '',
    type: '',
    description: ''
  };
  
  // 找到 AIR_SN 的位置，以此为分界线
  let airSnIndex = -1;
  for (let i = 0; i < lines.length; i++) {
    if (lines[i].includes('AIR_SN')) {
      airSnIndex = i;
      break;
    }
  }
  
  // 分割内容：AIR_SN 之前为问题描述部分，AIR_SN 及之后为环境信息部分
  const problemLines = airSnIndex >= 0 ? lines.slice(0, airSnIndex) : lines;
  const envContentLines = airSnIndex >= 0 ? lines.slice(airSnIndex) : [];
  
  // 解析问题描述部分
  let descriptionStarted = false;
  let descriptionLines = [];
  
  for (const line of problemLines) {
    if (line.includes('时间')) {
      const parts = line.split(/:|：/);
      if (parts.length >= 2) {
        problemInfo.time = parts.slice(1).join(':').trim();
      }
      continue;
    } else if (line.includes('问题')) {
      const parts = line.split(/:|：/);
      if (parts.length >= 2) {
        problemInfo.type = parts.slice(1).join(':').trim();
      }
      continue;
    } else if (line.includes('描述:') || line.includes('描述：')) {
      const parts = line.split(/:|：/);
      if (parts.length >= 2) {
        // 描述的第一行内容
        const firstLineDesc = parts.slice(1).join(':').trim();
        if (firstLineDesc) {
          descriptionLines.push(firstLineDesc);
        }
      }
      descriptionStarted = true;
      continue;
    } else if (descriptionStarted && line.trim() !== '') {
      // 描述的后续行
      descriptionLines.push(line.trim());
    }
  }
  
  // 合并描述的所有行
  problemInfo.description = descriptionLines.join('\n');
  
  // 处理环境信息部分
  for (const line of envContentLines) {
    if (line.trim() !== '') {
      envLines.push(line);
    }
  }
  
  // 格式化环境信息 - 每行显示两组键值对（四列）
  let envContent = '';
  if (envLines.length > 0) {
    // 将环境信息分组，每两个一组
    const rows = [];
    for (let i = 0; i < envLines.length; i += 2) {
      const row = [];
      
      // 处理第一个键值对
      const parts1 = envLines[i].split(/:|：/);
      if (parts1.length >= 2) {
        row.push({
          key: escapeHtml(parts1[0]),
          value: escapeHtml(parts1.slice(1).join(':'))
        });
      } else {
        row.push({
          key: '',
          value: escapeHtml(envLines[i])
        });
      }
      
      // 处理第二个键值对（如果存在）
      if (i + 1 < envLines.length) {
        const parts2 = envLines[i + 1].split(/:|：/);
        if (parts2.length >= 2) {
          row.push({
            key: escapeHtml(parts2[0]),
            value: escapeHtml(parts2.slice(1).join(':'))
          });
        } else {
          row.push({
            key: '',
            value: escapeHtml(envLines[i + 1])
          });
        }
      }
      
      rows.push(row);
    }
    
    // 生成HTML
    envContent = rows.map(row => {
      let rowHtml = '<div class="env-table-row">';
      
      // 第一个键值对
      rowHtml += `<div class="key-cell">${row[0].key}</div><div class="value-cell">${row[0].value}</div>`;
      
      // 第二个键值对（如果存在）
      if (row.length > 1) {
        rowHtml += `<div class="key-cell">${row[1].key}</div><div class="value-cell">${row[1].value}</div>`;
      }
      
      rowHtml += '</div>';
      return rowHtml;
    }).join('\n');
  }
  
  // 格式化问题描述信息
  let descContent = `
    <div class="problem-time-type">
      <div class="key-cell">时间</div>
      <div class="value-cell">${escapeHtml(problemInfo.time)}</div>
      <div class="key-cell">类型</div>
      <div class="value-cell">${escapeHtml(problemInfo.type)}</div>
    </div>
    <div class="problem-desc">
      <div class="key-cell">描述</div>
      <div class="value-cell description-value" id="problem-description-text">${escapeHtml(problemInfo.description)}</div>
      <div class="action-buttons">
        <button class="btn btn-sm btn-outline-primary copy-btn" id="copy-description-btn">拷贝</button>
        <button class="btn btn-sm btn-outline-primary translate-btn" id="translate-description-btn">翻译</button>
      </div>
    </div>
    <div class="problem-translation d-none" id="problem-translation">
      <div class="key-cell">译文</div>
      <div class="value-cell" id="translation-result"></div>
    </div>
  `;
  
  // 如果需要返回结果而不是更新DOM
  if (returnResult) {
    return {
      envContent,
      descContent
    };
  }
  
  // 否则更新DOM（兼容旧代码）
  // 显示环境信息
  if (envLines.length > 0) {
    environmentInfo.classList.remove('d-none');
    document.getElementById('envContent').innerHTML = envContent;
  } else {
    environmentInfo.classList.add('d-none');
  }
  
  // 显示问题描述
  if (descLines.length > 0) {
    problemDescription.classList.remove('d-none');
    document.getElementById('descriptionContent').innerHTML = descContent;
  } else {
    problemDescription.classList.add('d-none');
  }
}

// 转义HTML特殊字符，防止XSS攻击
function escapeHtml(unsafe) {
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

// 拷贝和翻译功能
document.addEventListener('DOMContentLoaded', function() {
  // 监听拷贝按钮点击事件
  document.body.addEventListener('click', function(event) {
    if (event.target.id === 'copy-description-btn') {
      const descriptionText = document.getElementById('problem-description-text').textContent;
      copyToClipboard(descriptionText);
      
      // 显示临时提示
      const copyBtn = document.getElementById('copy-description-btn');
      const originalText = copyBtn.textContent;
      copyBtn.textContent = '已复制';
      copyBtn.classList.add('btn-success');
      copyBtn.classList.remove('btn-outline-primary');
      
      setTimeout(() => {
        copyBtn.textContent = originalText;
        copyBtn.classList.remove('btn-success');
        copyBtn.classList.add('btn-outline-primary');
      }, 2000);
    }
    
    if (event.target.id === 'translate-description-btn') {
      const descriptionText = document.getElementById('problem-description-text').textContent;
      translateText(descriptionText);
    }
  });
});

// 复制文本到剪贴板
function copyToClipboard(text) {
  const textarea = document.createElement('textarea');
  textarea.value = text;
  textarea.style.position = 'fixed';
  textarea.style.opacity = '0';
  document.body.appendChild(textarea);
  textarea.select();
  document.execCommand('copy');
  document.body.removeChild(textarea);
}

// 翻译文本
function translateText(text) {
  // 显示翻译区域并设置加载状态
  const translationDiv = document.getElementById('problem-translation');
  const translationResult = document.getElementById('translation-result');
  translationDiv.classList.remove('d-none');
  translationResult.textContent = '翻译中...';
  
  // 简单的中文检测
  const isChinese = /[\u4e00-\u9fa5]/.test(text);
  
  if (isChinese) {
    // 如果已经是中文，显示提示
    translationResult.textContent = '文本已经是中文，无需翻译。';
    return;
  }
  
  // 使用IPC调用主进程进行翻译，避免在渲染进程中直接引入模块
  ipcRenderer.invoke('translate-text', { text, from: 'auto', to: 'zh-CN' })
    .then(result => {
      translationResult.innerHTML = escapeHtml(result.text).replace(/\n/g, '<br>');
    })
    .catch(error => {
      console.error('翻译出错:', error);
      translationResult.textContent = `翻译失败: ${error.message || '未知错误'}`;
    });
}

// 复制描述内容
function copyDescription() {
  const descText = document.getElementById('problem-description-text');
  if (descText) {
    const text = descText.textContent;
    copyToClipboard(text);
    
    // 显示复制成功提示
    showToast('复制成功！');
  }
}

// 翻译描述内容
function translateDescription() {
  const descText = document.getElementById('problem-description-text');
  if (descText) {
    const text = descText.textContent;
    
    // 显示译文行
    const translationRow = document.getElementById('problem-translation');
    const translationResult = document.getElementById('translation-result');
    
    if (translationRow && translationResult) {
      translationRow.classList.add('show');
      translationRow.style.display = 'table-row';
      
      // 调用真正的翻译函数
      translateText(text);
    }
  }
}

// 显示提示消息
function showToast(message) {
  // 创建或获取toast容器
  let toast = document.getElementById('toast-container');
  if (!toast) {
    toast = document.createElement('div');
    toast.id = 'toast-container';
    toast.className = 'toast-container';
    document.body.appendChild(toast);
  }
  
  // 创建toast消息
  const toastMessage = document.createElement('div');
  toastMessage.className = 'toast-message';
  toastMessage.textContent = message;
  
  // 添加到容器
  toast.appendChild(toastMessage);
  
  // 显示动画
  setTimeout(() => {
    toastMessage.classList.add('show');
  }, 10);
  
  // 3秒后自动消失
  setTimeout(() => {
    toastMessage.classList.remove('show');
    setTimeout(() => {
      if (toast.contains(toastMessage)) {
        toast.removeChild(toastMessage);
      }
    }, 300);
  }, 3000);
}



// 可拖拽分栏功能
document.addEventListener('DOMContentLoaded', function() {
  // 动态设置窗口标题
  try {
    const packagePath = path.join(__dirname, 'package.json');
    const packageData = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
    const version = packageData.version || '1.0.0';
    document.title = `Android 日志查看器 v${version}`;
  } catch (error) {
    console.warn('无法读取版本信息，使用默认标题:', error);
    document.title = 'Android 日志查看器';
  }
  
  const resizer = document.getElementById('resizer');
  const leftPanel = document.querySelector('.left-panel');
  const rightPanel = document.querySelector('.right-panel');
  let isResizing = false;
  
  resizer.addEventListener('mousedown', function(e) {
    isResizing = true;
    resizer.classList.add('dragging');
    document.body.style.cursor = 'col-resize';
    document.body.style.userSelect = 'none';
    
    e.preventDefault();
  });
  
  document.addEventListener('mousemove', function(e) {
    if (!isResizing) return;
    
    const containerRect = document.querySelector('.app-container').getBoundingClientRect();
    const newWidth = e.clientX - containerRect.left;
    
    // 限制最小和最大宽度
    const minWidth = 250;
    const maxWidth = containerRect.width * 0.6;
    
    if (newWidth >= minWidth && newWidth <= maxWidth) {
      leftPanel.style.width = newWidth + 'px';
      leftPanel.style.flex = 'none'; // 防止flex自动调整
    }
  });
  
  document.addEventListener('mouseup', function() {
    if (isResizing) {
      isResizing = false;
      resizer.classList.remove('dragging');
      document.body.style.cursor = '';
      document.body.style.userSelect = '';
    }
  });
  
  // 防止拖拽时选中文本
  resizer.addEventListener('selectstart', function(e) {
    e.preventDefault();
  });
  
  // 默认显示概述页面
  showOverview();
});